import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-demo8',
  templateUrl: './demo8.component.html'
})
export class Demo8Component implements OnInit {
  isAllSelected = false;
  indeterminate = false;
  setOfSelected = new Set();
  data = [];
  selectedArray = []; // 只做显示

  ngOnInit() {
    this.initData();
  }

  initData() {
    this.data = new Array(4).fill(0).map((item, index) => {
      return {
        id: index,
        value: `item${index + 1}`
      };
    });
  }

  allSelected(e: boolean) {
    this.data.forEach(({ value }) => this.updateSelected(value, e));
    this.refreshStatus();
  }

  itemSelected(value: string, e: boolean) {
    this.updateSelected(value, e);
    this.refreshStatus();
  }

  updateSelected(value: string, selected: boolean) {
    if (selected) {
      this.setOfSelected.add(value);
    } else {
      this.setOfSelected.delete(value);
    }

    this.selectedArray = Array.from(this.setOfSelected);
  }

  refreshStatus() {
    this.isAllSelected = this.data.every(({ value }) => this.setOfSelected.has(value));
    this.indeterminate = this.data.some(({ value }) => this.setOfSelected.has(value)) && !this.isAllSelected;
  }
}
